package com.zhupanlin.filter;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.http.MediaType;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.authentication.rememberme.AbstractRememberMeServices;
import org.springframework.util.ObjectUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;

/**
 * 描述信息：
 *
 * @author zhupanlin
 * @version 1.0
 * @date 2024/12/20 10:03
 */
public class MyUsernamePasswordAuthenticationFilter extends UsernamePasswordAuthenticationFilter {

    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {

        if (!request.getMethod().equals("POST")) {
            throw new AuthenticationServiceException("Authentication method not supported: " + request.getMethod());
        }
        // 判断是不是 json格式的
        if (request.getContentType().equalsIgnoreCase(MediaType.APPLICATION_JSON_VALUE)) {
            try {
                // 从 json 中获取username、password
                Map<String, Object> map = new ObjectMapper().readValue(request.getInputStream(), Map.class);
                String username = (String) map.get(getUsernameParameter());
                String password = (String) map.get(getPasswordParameter());
                String rememberMe = (String) map.get(AbstractRememberMeServices.DEFAULT_PARAMETER);
                if (ObjectUtils.isEmpty(username) || ObjectUtils.isEmpty(password) || ObjectUtils.isEmpty(rememberMe)) {
                    throw new AuthenticationServiceException("Username or password or rememberMe cannot be empty");
                }
                System.out.println("用户名:" + username + ", 密码:" + password + ", 记住我:" + rememberMe);
                request.setAttribute(AbstractRememberMeServices.DEFAULT_PARAMETER, rememberMe);
                UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(username, password);
                this.setDetails(request, usernamePasswordAuthenticationToken);
                Authentication authenticate = this.getAuthenticationManager().authenticate(usernamePasswordAuthenticationToken);
                return authenticate;
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }

        return super.attemptAuthentication(request, response);
    }
}
